<template>
  <div>
    <!-- 群聊通话界面 -->
    <template v-if="isGroupCall">
      <!-- 群聊顶部信息栏 -->
      <div class="video-call-header group-call-header">
        <div class="call-info">
          <q-avatar 
            size="48px" 
            class="call-avatar group-avatar"
            :style="getAvatarStyle(targetUserId)"
          >
            {{ getUserInitial(targetUserId) }}
          </q-avatar>
          <div class="call-details">
            <div class="call-title">{{ targetName }}</div>
            <div class="call-status">
              <q-icon 
                v-if="isConnecting"
                name="sync" 
                class="status-icon rotating"
                size="14px"
              />
              <q-icon 
                v-else-if="callStatus === '已接听' || callStatus === '已连接'"
                name="fiber_manual_record" 
                class="status-icon connected"
                size="8px"
              />
              <span class="status-text">{{ callStatus }}</span>
            </div>
          </div>
        </div>
        <q-btn
          flat
          round
          dense
          icon="close"
          class="close-btn"
          @click="handleClose"
        />
      </div>

      <!-- 群聊内容区域 -->
      <div class="video-call-content group-call-content">
        <!-- 呼叫中：显示成员列表 -->
        <template v-if="callStatus === '正在连接...' || callStatus === '呼叫中'">
          <div class="group-call-invite">
            <div class="invite-indicator">
              <q-icon 
                :name="isVoiceOnly ? 'phone_in_talk' : 'videocam'" 
                size="64px" 
                class="invite-icon"
              />
              <div class="invite-text">{{ isVoiceOnly ? '语音通话' : '视频通话' }}</div>
              <div class="invite-subtitle">正在呼叫...</div>
            </div>
            <div v-if="groupMembers && groupMembers.length > 0" class="group-members-list">
              <div class="members-title">参与成员 ({{ groupMembers.length }})</div>
              <div class="members-grid">
                <div
                  v-for="member in groupMembers"
                  :key="member.member_id"
                  class="member-card"
                  :class="{ 'is-current-user': member.member_id === currentUserId }"
                >
                  <q-avatar 
                    size="56px" 
                    class="member-avatar"
                    :style="getAvatarStyle(member.member_id)"
                  >
                    {{ getUserInitial(member.member_id) }}
                  </q-avatar>
                  <div class="member-name">{{ member.displayName || member.alias || member.member_id }}</div>
                  <div v-if="member.member_id === currentUserId" class="member-badge">我</div>
                </div>
              </div>
            </div>
          </div>
        </template>

        <!-- 已接听：显示视频网格（视频通话）或成员列表（语音通话） -->
        <template v-else>
          <div class="group-call-active">
            <!-- 视频通话：显示视频网格 -->
            <template v-if="!isVoiceOnly">
              <div class="video-grid">
                <!-- 本地视频 -->
                <div class="video-item local-video-item">
                  <video
                    ref="localVideoRef"
                    autoplay
                    playsinline
                    muted
                    class="group-video"
                    :class="{ 'video-active': isLocalVideoActive, 'video-hidden': isVideoOff }"
                  />
                  <div v-if="!isLocalVideoActive || isVideoOff" class="video-placeholder">
                    <q-avatar
                      size="48px"
                      class="placeholder-avatar"
                      :style="getAvatarStyle(currentUserId)"
                    >
                      {{ getUserInitial(currentUserId) }}
                    </q-avatar>
                    <div class="placeholder-name">{{ getUserInitial(currentUserId) }}</div>
                    <div v-if="isVideoOff" class="video-off-badge">
                      <q-icon name="videocam_off" size="16px" />
                    </div>
                  </div>
                  <div class="video-label">我</div>
                </div>
                <!-- 远程视频（占位，实际需要根据参与者动态生成） -->
                <div class="video-item remote-video-item">
                  <video
                    ref="remoteVideoRef"
                    autoplay
                    playsinline
                    class="group-video"
                    :class="{ 'video-active': isRemoteVideoActive }"
                  />
                  <div v-if="!isRemoteVideoActive" class="video-placeholder">
                    <q-avatar
                      size="48px"
                      class="placeholder-avatar"
                      :style="getAvatarStyle(targetUserId)"
                    >
                      {{ getUserInitial(targetUserId) }}
                    </q-avatar>
                    <div class="placeholder-name">{{ targetName }}</div>
                  </div>
                  <div class="video-label">{{ targetName }}</div>
                </div>
              </div>
            </template>

            <!-- 语音通话：显示成员列表 -->
            <template v-else>
              <div class="voice-call-members">
                <div class="members-title">通话中 ({{ (groupMembers?.length || 0) + 1 }})</div>
                <div class="members-grid">
                  <div
                    v-for="member in groupMembers"
                    :key="member.member_id"
                    class="member-card active"
                    :class="{ 'is-current-user': member.member_id === currentUserId }"
                  >
                    <q-avatar 
                      size="64px" 
                      class="member-avatar"
                      :style="getAvatarStyle(member.member_id)"
                    >
                      {{ getUserInitial(member.member_id) }}
                    </q-avatar>
                    <div class="member-name">{{ member.displayName || member.alias || member.member_id }}</div>
                    <div v-if="member.member_id === currentUserId" class="member-badge">我</div>
                    <div class="member-status">
                      <q-icon name="fiber_manual_record" class="status-dot" size="8px" />
                      <span>通话中</span>
                    </div>
                  </div>
                </div>
              </div>
            </template>
          </div>
        </template>
      </div>
    </template>

    <!-- 单聊通话界面（原有界面） -->
    <template v-else>
      <!-- 顶部信息栏 -->
      <div class="video-call-header">
        <div class="call-info">
          <q-avatar 
            size="48px" 
            class="call-avatar"
            :style="getAvatarStyle(targetUserId)"
          >
            {{ getUserInitial(targetUserId) }}
          </q-avatar>
          <div class="call-details">
            <div class="call-title">{{ targetName }}</div>
            <div class="call-status">
              <q-icon 
                v-if="isConnecting"
                name="sync" 
                class="status-icon rotating"
                size="14px"
              />
              <q-icon 
                v-else-if="callStatus === '已接听' || callStatus === '已连接'"
                name="fiber_manual_record" 
                class="status-icon connected"
                size="8px"
              />
              <span class="status-text">{{ callStatus }}</span>
            </div>
          </div>
        </div>
        <q-btn
          flat
          round
          dense
          icon="close"
          class="close-btn"
          @click="handleClose"
        />
      </div>

      <!-- 视频内容区域 -->
      <div class="video-call-content">
      <div 
        class="video-container"
        :class="{ 'voice-only': isVoiceOnly }"
      >
        <!-- 远程视频 -->
        <div class="remote-video-wrapper">
          <video
            v-if="!isVoiceOnly"
            ref="remoteVideoRef"
            autoplay
            playsinline
            class="remote-video"
            :class="{ 'video-active': isRemoteVideoActive }"
          />
          <div 
            v-if="!isRemoteVideoActive || isVoiceOnly"
            class="video-placeholder"
          >
            <div v-if="isVoiceOnly" class="voice-call-indicator">
              <q-icon name="phone_in_talk" size="36px" />
              <span>语音通话</span>
            </div>
            <div v-else-if="!isRemoteVideoActive" class="video-call-indicator">
              <q-icon name="videocam" size="36px" />
              <span>等待对方开启视频</span>
            </div>
          </div>
        </div>

        <!-- 本地视频 -->
        <div 
          v-if="!isVoiceOnly"
          class="local-video-wrapper"
          :class="{ 'video-hidden': isVideoOff }"
        >
          <video
            ref="localVideoRef"
            autoplay
            playsinline
            muted
            class="local-video"
            :class="{ 'video-active': isLocalVideoActive }"
          />
          <div 
            v-if="!isLocalVideoActive || isVideoOff"
            class="local-video-placeholder"
          >
            <q-avatar
              size="48px"
              class="local-placeholder-avatar"
              :style="getAvatarStyle(currentUserId)"
            >
              {{ getUserInitial(currentUserId) }}
            </q-avatar>
            <div v-if="isVideoOff" class="local-video-off-indicator">
              <q-icon name="videocam_off" size="18px" />
            </div>
          </div>
        </div>
        </div>
      </div>
    </template>

    <!-- 底部控制栏（群聊和单聊共用） -->
    <div class="video-call-controls">
      <div class="controls-row">
        <!-- 静音按钮 -->
        <div class="control-item">
          <q-btn
            round
            unelevated
            class="control-btn mute-btn"
            :class="{ 'active': isMuted }"
            :icon="isMuted ? 'mic_off' : 'mic'"
            size="lg"
            @click="toggleMute"
          />
          <span class="control-label">{{ isMuted ? '取消静音' : '静音' }}</span>
        </div>

        <!-- 视频通话时显示视频开关按钮 -->
        <div v-if="!isVoiceOnly" class="control-item">
          <q-btn
            round
            unelevated
            class="control-btn video-btn"
            :class="{ 'active': isVideoOff }"
            :icon="isVideoOff ? 'videocam_off' : 'videocam'"
            size="lg"
            @click="toggleVideo"
          />
          <span class="control-label">{{ isVideoOff ? '开启视频' : '关闭视频' }}</span>
        </div>

        <!-- 语音通话时显示升级到视频按钮 -->
        <div v-if="isVoiceOnly" class="control-item">
          <q-btn
            round
            unelevated
            class="control-btn upgrade-btn"
            icon="videocam"
            size="lg"
            @click="switchToVideo"
            title="升级到视频通话"
          />
          <span class="control-label">视频</span>
        </div>

        <!-- 视频通话时显示切换到语音按钮 -->
        <div v-if="!isVoiceOnly" class="control-item">
          <q-btn
            round
            unelevated
            class="control-btn downgrade-btn"
            icon="phone"
            size="lg"
            @click="switchToVoiceOnly"
            title="切换到语音通话"
          />
          <span class="control-label">语音</span>
        </div>

        <!-- 挂断按钮（居中，更大） -->
        <div class="control-item end-call-item">
          <q-btn
            round
            unelevated
            class="control-btn end-call-btn"
            icon="call_end"
            size="lg"
            @click="handleEndCall"
          />
          <span class="control-label end-call-label">挂断</span>
        </div>
      </div>
    </div>

    <!-- 加载提示 -->
    <q-inner-loading :showing="isConnecting" class="call-loading">
      <div class="loading-content">
        <q-spinner size="60px" color="white" class="loading-spinner" />
        <div class="loading-text">{{ loadingText }}</div>
        <div class="loading-subtitle">请稍候...</div>
      </div>
    </q-inner-loading>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { getAvatarStyle } from '@/utils/avatar'

const props = defineProps<{
  targetUserId: string
  targetName: string
  currentUserId: string
  getUserInitial: (userId: string) => string
  isVoiceOnly?: boolean
  isGroupCall?: boolean // 是否是群聊通话
  groupMembers?: Array<{ member_id: string; displayName: string; alias?: string; avatar?: string; role?: number }> // 群聊成员列表
  isConnecting: boolean
  loadingText: string
  callStatus: string
  isMuted: boolean
  isVideoOff: boolean
  isLocalVideoActive: boolean
  isRemoteVideoActive: boolean
  toggleMute: () => void
  toggleVideo: () => void
  switchToVoiceOnly: () => void
  switchToVideo: () => void
  handleEndCall: () => void
  handleClose: () => void
}>()

// 视频元素引用
const localVideoRef = ref<HTMLVideoElement | null>(null)
const remoteVideoRef = ref<HTMLVideoElement | null>(null)

// 暴露 ref 给父组件
defineExpose({
  localVideoRef,
  remoteVideoRef
})
</script>

<style lang="sass" scoped>
// 群聊通话专用样式
.group-call-header
  .group-avatar
    border: 3px solid rgba(7, 193, 96, 0.3)

.group-call-content
  padding: 24px

.group-call-invite
  display: flex
  flex-direction: column
  align-items: center
  justify-content: center
  height: 100%
  gap: 32px

  .invite-indicator
    display: flex
    flex-direction: column
    align-items: center
    gap: 16px
    color: rgba(255, 255, 255, 0.9)

    .invite-icon
      width: 100px !important
      height: 100px !important
      min-width: 100px !important
      min-height: 100px !important
      font-size: 50px !important
      color: #07C160
      flex-shrink: 0
      display: flex
      align-items: center
      justify-content: center
      line-height: 1
      aspect-ratio: 1
      box-sizing: border-box
      filter: drop-shadow(0 4px 12px rgba(7, 193, 96, 0.4))

    .invite-text
      font-size: 20px
      font-weight: 500
      letter-spacing: 0.3px
      color: rgba(255, 255, 255, 0.9)
      text-shadow: 0 2px 4px rgba(0, 0, 0, 0.3)

    .invite-subtitle
      font-size: 14px
      color: rgba(255, 255, 255, 0.75)
      font-weight: 400
      letter-spacing: 0.2px

  .group-members-list
    width: 100%
    max-width: 600px

    .members-title
      font-size: 14px
      color: rgba(255, 255, 255, 0.7)
      margin-bottom: 16px
      text-align: center
      font-weight: 500

    .members-grid
      display: grid
      grid-template-columns: repeat(auto-fill, minmax(100px, 1fr))
      gap: 16px
      justify-items: center

      .member-card
        display: flex
        flex-direction: column
        align-items: center
        gap: 8px
        padding: 12px
        border-radius: 12px
        background: rgba(255, 255, 255, 0.05)
        transition: all 0.3s ease
        position: relative
        width: 100%
        max-width: 100px

        &:hover
          background: rgba(255, 255, 255, 0.1)
          transform: translateY(-2px)

        &.is-current-user
          background: rgba(7, 193, 96, 0.15)
          border: 1px solid rgba(7, 193, 96, 0.3)

        .member-avatar
          box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3)

        .member-name
          font-size: 12px
          color: rgba(255, 255, 255, 0.9)
          text-align: center
          overflow: hidden
          text-overflow: ellipsis
          white-space: nowrap
          width: 100%

        .member-badge
          position: absolute
          top: 8px
          right: 8px
          background: #07C160
          color: white
          font-size: 10px
          padding: 2px 6px
          border-radius: 10px
          font-weight: 500

.group-call-active
  width: 100%
  height: 100%

  .video-grid
    display: grid
    grid-template-columns: repeat(auto-fit, minmax(200px, 1fr))
    gap: 16px
    height: 100%
    padding: 16px

    .video-item
      position: relative
      border-radius: 12px
      overflow: hidden
      background: rgba(0, 0, 0, 0.5)
      aspect-ratio: 16 / 9
      min-height: 150px

      .group-video
        width: 100%
        height: 100%
        object-fit: cover
        opacity: 0
        transition: opacity 0.3s ease

        &.video-active
          opacity: 1

        &.video-hidden
          opacity: 0.3
          filter: grayscale(100%)

      .video-placeholder
        position: absolute
        top: 0
        left: 0
        width: 100%
        height: 100%
        display: flex
        flex-direction: column
        align-items: center
        justify-content: center
        gap: 12px
        background: rgba(0, 0, 0, 0.6)

        .placeholder-avatar
          box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3)

        .placeholder-name
          font-size: 14px
          color: rgba(255, 255, 255, 0.9)
          font-weight: 500

        .video-off-badge
          position: absolute
          bottom: 8px
          right: 8px
          background: rgba(255, 59, 48, 0.8)
          color: white
          padding: 4px 8px
          border-radius: 4px
          display: flex
          align-items: center
          gap: 4px

      .video-label
        position: absolute
        bottom: 8px
        left: 8px
        background: rgba(0, 0, 0, 0.6)
        color: white
        padding: 4px 8px
        border-radius: 4px
        font-size: 12px
        font-weight: 500

      &.local-video-item
        border: 2px solid rgba(7, 193, 96, 0.5)

  .voice-call-members
    display: flex
    flex-direction: column
    align-items: center
    gap: 24px
    padding: 24px
    height: 100%
    overflow-y: auto

    .members-title
      font-size: 16px
      color: rgba(255, 255, 255, 0.9)
      font-weight: 500

    .members-grid
      display: grid
      grid-template-columns: repeat(auto-fill, minmax(120px, 1fr))
      gap: 20px
      width: 100%
      max-width: 600px

      .member-card
        display: flex
        flex-direction: column
        align-items: center
        gap: 12px
        padding: 16px
        border-radius: 16px
        background: rgba(255, 255, 255, 0.08)
        transition: all 0.3s ease
        position: relative

        &.active
          background: rgba(7, 193, 96, 0.15)
          border: 1px solid rgba(7, 193, 96, 0.3)

        &.is-current-user
          background: rgba(7, 193, 96, 0.2)
          border: 2px solid rgba(7, 193, 96, 0.5)

        .member-avatar
          box-shadow: 0 4px 16px rgba(0, 0, 0, 0.4)
          border: 2px solid rgba(255, 255, 255, 0.2)

        .member-name
          font-size: 13px
          color: rgba(255, 255, 255, 0.9)
          text-align: center
          font-weight: 500

        .member-badge
          position: absolute
          top: 8px
          right: 8px
          background: #07C160
          color: white
          font-size: 10px
          padding: 2px 6px
          border-radius: 10px
          font-weight: 500

        .member-status
          display: flex
          align-items: center
          gap: 4px
          font-size: 11px
          color: rgba(255, 255, 255, 0.7)

          .status-dot
            color: #07C160
            animation: pulse-dot 2s ease-in-out infinite

// 单聊样式在父组件 VideoCall.vue 中定义
</style>

